package com.itmuch.box.controller.front.member;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.itmuch.box.core.base.BaseController;
import com.itmuch.box.core.security.SubjectUtil;
import com.itmuch.box.domain.member.entity.Member;
import com.itmuch.box.domain.member.vo.MemberChangePwdVo;
import com.itmuch.box.service.member.MemberService;
import com.itmuch.box.util.PasswordEncoderUtil;

/**
 * 个人信息
 * @author zhouli
 */
@Controller
@RequestMapping("/member")
public class MemberCenterChangePwdController extends BaseController {
    @Resource
    private MemberService memberService;

    @RequestMapping(value = "/change-pwd", method = RequestMethod.GET)
    public String change() {
        return "front/member/center/change-pwd";
    }

    @RequestMapping(value = "/change-pwd", method = RequestMethod.POST)
    public String changePwd(@Valid @ModelAttribute("info") MemberChangePwdVo vo, BindingResult result, RedirectAttributes ra,
            HttpServletRequest req) {
        // JSR 校验成功
        if (!result.hasErrors()) {
            String oldPassword = vo.getOldPassword();
            String password = vo.getPassword();

            Integer id = SubjectUtil.getSubjectId();
            Member member = this.memberService.findOne(id);
            String pwdInDB = member.getPassword();

            // 旧密码验证成功
            if (PasswordEncoderUtil.matches(oldPassword, pwdInDB)) {
                String encode = PasswordEncoderUtil.encode(password);
                member.setPassword(encode);
                this.memberService.update(member);

                ra.addFlashAttribute("msg", "密码修改成功");
                ra.addFlashAttribute("nextUrl", req.getContextPath() + "/member/change-pwd");
                return String.format("redirect:/%s", "success");
            }
            // 旧密码校验失败
            else {
                result.rejectValue("oldPassword", null, "原密码不正确.");
            }
        }
        // JSR 校验失败
        return "front/member/center/change-pwd";
    }

}
